package tech.dongling.boot.plugins.impl;

import cn.hutool.core.util.HexUtil;
import cn.hutool.crypto.SmUtil;
import cn.hutool.crypto.symmetric.SM4;
import cn.hutool.json.JSONUtil;
import tech.dongling.boot.anno.Order;
import tech.dongling.boot.common.base.ApiResponse;
import tech.dongling.boot.plugins.ResponsePlugin;

import java.util.Properties;

// 加密插件（@Order=10）
@Order(10)
public class EncryptPlugin implements ResponsePlugin {
    private SM4 sm4;

    @Override
    public void init(Properties config) {
        if ("true".equals(config.getProperty("crypto.enabled"))) {
            String key = config.getProperty("crypto.sm4.key");
            sm4 = SmUtil.sm4(HexUtil.decodeHex(key));
        }
    }

    @Override
    public void process(ApiResponse response) throws Exception {
        if (sm4 != null && response.getData() != null) {
            response.setData(sm4.encryptBase64(JSONUtil.toJsonStr(response.getData())));
        }
    }
}